library(optparse)
library(tidyverse)
library(magrittr)

configGet <- function(configData, key) {
  configData %>%
    filter(arg == key) %>%
    .$value
}

option_list <- list(
  make_option("--phypath", default = "AllMet_Raw.txt", type = "character", help = "The path to the table data read"),
  make_option("--envpath", default = "list.txt", type = "character", help = "The package path of the output image"),
  make_option("--filepath", default = "./", type = "character", help = "package path of image output"),
  make_option("--cc", default = "calculate_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read_tsv(opt$cc, col_names = F) %>%
  set_colnames(c("arg", "value"))

method <- configGet(configData, "analysisKind")

suppressMessages(library("vegan"))
pdata <- read.delim(opt$phypath, header = TRUE, check.name = F)
rownames(pdata) <- pdata[, 1]; pdata <- pdata[, -1]
pdata <- data.frame(t(pdata))
edata <- read.delim(opt$envpath, header = T, check.name = F)
rename <- edata[, 1]; edata <- edata[, -1]; rownames(edata) <- rename
dec <- decorana(veg = pdata)
if (method == "RDA") {
  sp1 <- rda(pdata ~ ., edata)
}
if (method == "CCA") {
  sp1 <- cca(pdata ~ ., edata)
}
if (method != "CCA" & method != "RDA") { cat(paste0("error method:", method)); quit() }
new <- sp1$CCA
RDA <- sp1$CCA$eig
dd <- round(RDA / sum(RDA), 4) * 100; rownames <- names(dd)
dd <- as.character(paste0(dd, "%"))
rda_cca_percent <- data.frame(percent = dd)
rownames(rda_cca_percent) <- rownames
write.csv(rda_cca_percent, paste0(opt$filepath, "/", "percent.csv"), col.names = NA)
write.csv(as.data.frame(new$u), paste0(opt$filepath, "/", "samples.csv"), col.names = NA)
write.csv(as.data.frame(new$v), paste0(opt$filepath, "/", "species.csv"), col.names = NA)
write.csv(as.data.frame(new$biplot), paste0(opt$filepath, "/", "envi.csv"), col.names = NA)

